import {Request, Response, Router} from "express";
import logger from "../logger";
import axios from "axios";
import {config} from "../config/config";
import {users_add_ips, users_findUpdate} from "./usersRouter";
import {delay} from "../tools";
import {handlerGame} from "../services/gameService";
import {Game_login} from "../types/clientType";
import {handler_update, handlerEcpm} from "../services/clientService";
import {GamesModel} from "../models/gamesModel";

require('express-async-errors');

export const client_router: Router = Router();

client_router.post('/login', async (req: Request, res: Response) => {
    try {
        const login_data: Game_login = req.body.login;
        const system_data = req.body.system;
        // 获取 open_id 并且判断数据是否有问题
        const login_result: any = await axios.get(config.code2Session, {params: login_data});
        if (login_result.data.error !== 0) {
            res.json(login_result.data);
            logger.error({msg: 'get code2Session', data: login_result.data});
            return;
        }
        // 获取 config 并且处理未注册游戏问题
        const game_data: any = await handlerGame(login_data);
        res.json({
            openid: login_result.data.openid,
            hyd_data: game_data.config
        })
        users_findUpdate(login_data.appid, login_result.data.openid, {
            openid: login_result.data.openid,
            appid: login_data.appid,
            unionid: login_result.data.unionid,
            session_key: login_result.data.session_key,
            anonymous_openid: login_result.data.anonymous_openid
        }).then(() => {
            const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
            if (typeof ip === 'string') {
                users_add_ips(login_data.appid, login_result.data.openid, ip).then();
            }
        });
    } catch (err) {
        res.json('err');
        logger.error({msg: 'login', err: err});
    }
});

client_router.post('/postad', async (req: Request, res: Response) => {
    const data = req.body
    res.json('ok');
    await delay();
    await handlerEcpm(data);
});

client_router.get('/update_ecpm', async (req: Request, res: Response) => {
    const appid = req.query.appid as string;
    const date = req.query.date as string;
    res.json('ok');
    const data = await handler_update(appid,date);
});

